﻿require.config({
    paths: {
        jquery: "../../jquery.min"
        , liger: "../../ligerUI/js/ligerui.min"
    }
});
require(["jquery", "liger"], function ($) {
    var userStore = {};
    var Users = top.Users;
    var userTree;
    var chatingUserID;
    var userListMenu;
    var CurrentUser = { Id: null, Name: "" };
    var ChatConn = top.ChatConn;
    var historyGrid;
    var HeightDiff = 36;
    var roleStore = {
        "88": "主管1"
        , "101": "主管2"
        , "110": "主管3"
        , "42": "监理企业"
        , "15": "施工企业"
        , "76": "县级主管"
        , "86": "市级主管"
        , "96": "省级主管"
        , "other": "其他"
    };
    var REQUEST_PATH = "ChatHandler.ashx";

    $.ligerDefaults.Grid.formatters['customDate'] = DateFormatConvert;

    //给聊天页面添加订阅
    function AddChatListener() {
        top.ChatSubscibeEvents["Chat"] = {
            func: ShowData
            , context: window
        };
    }

    //有很大的优化余地
    function ShowData(msgs) {
        var c;
        for (var i = 0, len = msgs.length; i < len; i++) {
            c = Chat.ChatManager.getChat(msgs[i].Sender);
            if (!c) {
                c = Chat.Create(msgs[i].Sender);
            }
            c.PushChatList([msgs[i]]);
            c.Show();
        }
    }

    function ShowInitChat() {
        if (top.ChatStore.length > 0)
            ShowData(top.ChatStore);
    }

    //日期格式转化
    function DateFormatConvert(date) {
        var dateStr = date;
        if (typeof date == "object") {
            dateStr = date.toLocaleString();
        } else if (typeof date == "string") {
            dateStr = new Date(date.replace(/-/g, "/").replace(/\..+$/, "").replace(/T/, " ")).toLocaleString();
        }
        return dateStr.replace(/^([\d-]+)T([\d:]+).+$/, "$1 $2");
    }

    //控制用户列表显示长度
    function nodeTextToShort(text) {
        var MAX_NODETEXT_LENGTH = 16;
        if (text.length > MAX_NODETEXT_LENGTH) {
            return text.substring(0, MAX_NODETEXT_LENGTH - 1) + "...";
        }
        return text;
    }

    //创建用户库
    function InitUser() {
        for (var i = 0; i < Users.length; i++) {
            userStore[top.Users[i].UserGuid] = Users[i];
        }
    }

    //获取用户列表
    function BindUserRoleList() {
        var data = [], roleName, user, roleCount = 1, _roleStoreTemp = {};
        var roleIcon = '../Scripts/ligerUI/skins/icons/customers.gif';
        var userIcon = '../Scripts/ligerUI/skins/icons/memeber.gif';

        for (var i = 0, len = Users.length; i < len; i++) {
            user = Users[i];
            if (user.UserGuid == CurrentUser.Id) continue;
            if (!_roleStoreTemp[user.RoleId]) {
                _roleStoreTemp[user.RoleId] = 1;
                data.push({ id: user.RoleId, pid: 0, text: roleStore[user.RoleId] || roleStore["other"], icon: roleIcon, isexpand: false });
            }
            data.push({ id: user.UserGuid, pid: user.RoleId, text: nodeTextToShort(user.Name), icon: userIcon });
        }

        window.oncontextmenu = function () { return false };

        userListMenu = $.ligerMenu({ top: 100, left: 100, width: 120, items:
            [
                { text: '发起聊天', click: itemclick, icon: "comment" }
                , { line: true }
                , { text: '历史记录', click: ShowHistory, icon: "attibutes" }
            ]
        });

        userTree = $("#userTree").ligerTree({
            data: data,
            idFieldName: 'id',
            slide: true,
            parentIDFieldName: 'pid',
            nodeWidth: 280,
            checkbox: false,
            onContextmenu: function (node, e) {
                if (node.data.pid != 0) {
                    chatingUserID = node.data.id;
                    userListMenu.show({ top: e.pageY, left: e.pageX });
                }
                return false;
            }
        });
    }

    function PageInit() {
        //调整窗口高度
        $.ligerui.win.createTaskbar();
        $.ligerui.win.removeTaskbar = function () { };
        $("#layout1").ligerLayout({
            minLeftWidth: 200,
            leftWidth: 200,
            heightDiff: -HeightDiff
        });
    }

    function ShowHistory() {
        if (!historyGrid) {
            historyGrid = $("#historyGrid").ligerGrid({
                width: "99%"
                , columns: [
                    { display: '发信人', align: 'center', width: 200
                        , render: function (item) {
                            return roleStore[item.Sender] || userStore[item.Sender].Name;
                        }
                    },
                    { display: '发送时间', name: 'SendTime', width: 200, type: "customDate" },
                    { display: '内容', name: 'MsgText', width: 500 },
                    { name: "ID", hide: true }
                ]
                , rownumbers: true
                , checkbox: false
                , enabledSort: false
                , usePager: true
                , pageSizeOptions: [20, 30, 40, 50]
                , pageSize: 20
                , isScroll: true
                , heightDiff: -HeightDiff
                , height: "99%"
                , fixedCellHeight: false
                , selectRowButtonOnly: true
            });
        };
        var stamp = new Date() - 0;
        $.getJSON(REQUEST_PATH, { Func: "getHistory", Sender: chatingUserID, TimeStamp: stamp }, function (data) {
            historyGrid.loadData({ Rows: data });
        });
    }

    function itemclick() {
        var c = Chat.ChatManager.ChatStore[chatingUserID]
        if (!$.ligerui.managers[chatingUserID]) c = Chat.Create(chatingUserID);
        c.Show();
    }

    // 聊天框相关
    function Chat(chating, chatData) {
        this.ChatingName = userStore[chating].Name || "陌生人";
        this.Chating = chating;
        this.Win = null;
        this.IsSending = false;

        var html = "<div><div class='msg-container' style='height:200px;overflow-x:hidden;overflow-y:auto;background:linen;'></div>";
        html += "<textarea class='chatInput' style='width:97%;background:linen;border:none;border-top:solid 2px lightslategrey;padding: 5px;'></textarea></div>";
        this.WinDom = $(html);
        this.PushChatList(chatData || []);
    }

    Chat.ChatManager = {
        ChatStore: {}
        , getChat: function (chating) {
            return this.ChatStore[chating];
        }
    };

    Chat.Create = function (chating, chatData) {
        var c = new Chat(chating, chatData);
        Chat.ChatManager.ChatStore[chating] = c;
        return c;
    }

    Chat.prototype.PushChatList = function (msgList) {
        var container = this.WinDom.find(".msg-container");
        var html = "";
        for (var i = 0; i < msgList.length; i++) {
            html += "<div class='msg' style='width:100%;'><p class='msg-head' style='color:blue;'>";
            html += "   <font>" + userStore[msgList[i].Sender].Name + "</font>";
            html += "   <l class='msg-time' style='margin-left:10px;'>" + DateFormatConvert(msgList[i].SendTime) + "</l></p>";
            html += "<div class='msg-text' style='padding-left:15px;'>" + msgList[i].MsgText + "</div></div>";
        }
        container.append(html);
    }

    Chat.prototype.Show = function () {
        var _self = this;

        if (!_self.Win) {
            var _dom = _self.WinDom;
            _self.Win = $.ligerDialog.open({
                target: _dom
                , id: _self.Chating
                , title: _self.ChatingName
                , width: 400
                , modal: false
                , showMin: true
                , isHidden: false
                , slide: false
                , allowClose: false
                , buttons: [
                    {
                        text: '发送'
                        , onclick: function () {
                            var sendText = $(".chatInput", _self.WinDom).val().replace(/(^[\s]+)|([\s]+$)/g, "");
                            if (sendText) _self.Send(sendText);
                        }
                    }
                    , {
                        text: "关闭"
                        , onclick: function () {
                            delete Chat.ChatManager.ChatStore[_self.Chating];
                            _self.Win.close();
                            delete $.ligerui.managers[_self.Chating];
                        }
                    }
                ]
            });
        } else {
            _self.Win.active();
        }
    }
    Chat.prototype.Send = function (text) {
        var _self = this;
        if (_self.IsSending) return;
        _self.IsSending = true;

        var SendData = {
            Func: "Send",
            Receiver: _self.Chating,
            Sender: CurrentUser.Id,
            MsgText: text
        }

        function sendCallBack(rst) {
            var msgContainer = $(".msg-container", _self.WinDom)
                , sendState = rst.Result == "success"
                , sendTime = DateFormatConvert(rst.SendTime)
                , html = "<div class='msg' style='width:100%;'>";

            html += "<p class='msg-head' style='color:blue;'><font>" + CurrentUser.Name + "</font><l class='msg-time' style='margin-left:10px;'>" + sendTime + "</l></p>";
            if (sendState) {
                html += "<div class='msg-text' style='padding-left:15px;'>" + text + "</div></div>";
                $(".chatInput", _self.WinDom).val("");
            } else {
                html += "<div class='msg-error' style='padding-left:15px;color:grey;'>消息发送失败</div></div>";
            }
            msgContainer.append(html);
            _self.IsSending = false;
        }
        ChatConn.send(SendData, sendCallBack);
    }
    window.Chat = Chat;

    //初始化操作
    $(function () {
        InitUser();
        CurrentUser.Id = $("#hidCurrentUser").val();
        CurrentUser.Name = userStore[CurrentUser.Id].Name;
        BindUserRoleList();
        PageInit();
        AddChatListener();
        ShowInitChat();
    });
});